'use strict'

import axios from 'axios'
import qs from 'qs'
import { Message, Loading } from 'element-ui'
import Router from '@/router/index'
import store from '@/store/store'
// import router from "../../router";
// axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : '/request';

let loading;
//内存中正在请求的数量
let loadingNum = 0;
function startLoading() {
    if (loadingNum == 0) {
        loading = Loading.service({
            lock: true,
            text: '拼命加载中...',
            background: 'rgba(0,0,0,0.8)',
        })
    }
    //请求数量加1
    loadingNum++;
}
function endLoading() {
    //请求数量减1
    loadingNum--
    if (loadingNum <= 0) {
        loading.close()
    }
}

const Axios = axios.create({
    timeout: 5000,
    responseType: "json",
    withCredentials: true, // 是否允许带cookie
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8", 'x-requested-with': 'XMLHttpRequest'
    }
});


Axios.interceptors.request.use( //请求前
    config => {
        startLoading()
        if (config.method === "post" && config.headers['Content-Type'] !== "multipart/form-data") {
            if (config.method === "post" && config.headers['Content-Type'] == "application/json") {
                config.data = config.data;
            } else {
                config.data = qs.stringify(config.data);
            }
        }

        config.timeout = config.headers['Content-Type'] === "multipart/form-data" ? '7200000' : '7200000'
        config.headers["session_id"] = window.sessionStorage.sessionId
        return config;
    },
    error => {
        Message({
            showClose: true,
            message: "请求超时",
            type: 'warning'
        });
    }
)

Axios.interceptors.response.use( //处理数据
    res => {
        endLoading()
        if (res.status == 200) {
            if (res.data.type == 'application/vnd.ms-excel') {
                return res
            } else if (res.data.type == 'application/octet-stream') {
                return res;
            } else if (res.data.status == "SUCCESS") {
                return res;
            } else if (res.data.status == "REDIRECT") {
                window.open(res.data.result, "_self")
            } else if (res.data.status == "ERROR") {
                Message.error(res.data.errorMessage);
                return Promise.reject(res.data.errorMessage);
            }
        }
    },
    error => {
        endLoading()
        if (error.response.status) {
            switch (error.response.status) {
                case 401:
                    router.replace({
                        path: '/login',
                        query: {
                            redirect: router.currentRoute.fullPath
                        }
                    });
                    break;
                case 404:
                    Message.error('网络请求不存在');
                    break;
                default:
                    Message.error(error.response.data.message);
            }
            let errorInfo = error;
            return Promise.reject(errorInfo);
        }
    }
)
export default Axios
